package com.safeluck.floatwindow;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


import com.safeluck.floatwindow.util.FileUtil;
import com.safeluck.floatwindow.util.SDCardHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getCanonicalName();
    private String waizhiPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        File file = getFilesDir();
        Log.i(TAG, "onCreate: getFileDir path:"+file.getPath());
        new Thread(){
            @Override
            public void run() {
                super.run();
                String FILENAME = "hello_file";
                String string = "hello world!";

                try {
                    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(string.getBytes());
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    File file1 = new File(getApplicationContext(). getExternalCacheDir(),FILENAME);
                    FileOutputStream fileOutputStream = new FileOutputStream(file1);
                    fileOutputStream.write("hello,jfdksla".getBytes());
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();



    }

    public  void stop(View view){
//        Log.i(TAG, "stop: isRecord="+VideoRecorder.getInstance().isRecord());
        VideoRecorder.getInstance().stopRecordVideo(this.getApplicationContext());
//        Log.i(TAG, "stop: isRecord="+VideoRecorder.getInstance().isRecord());



        boolean isTFCardMounted=SDCardHelper.isSDCardMounted();
        DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
        Log.i(TAG,"width="+displayMetrics.widthPixels+"height="+displayMetrics.heightPixels+" density="+displayMetrics.density+"  densityDpi="+displayMetrics.densityDpi);
        Log.i(TAG,"isTFcard="+isTFCardMounted);
        if (isTFCardMounted){

        }else{
            return;
        }


        List<String> paths = SDCardHelper.getExtSDCardPathList();
        for (String path:
                paths) {
            if (path.contains("sdcard1")){
                Log.i(TAG, "init: sdcard1="+path);
                FileUtil.createFile(path+"/DCIM","2.txt");
                waizhiPath = path;
                pathS = path+"/AnYun_VIDEO";
            }
        }
        Log.i(TAG, "init: 全路径="+pathS+System.currentTimeMillis()+".mp4");

        //判断剩余可用空间 如果<20MB,
        waizhiPath = pathS;
        Log.i(TAG, "starter: waizhipath="+waizhiPath);
        Log.i(TAG, "starter: available space="+       SDCardHelper.getWaiZhiSDCardAvailableSize(waizhiPath));

        //提示用户可用空间不足，是否开启循环录制，开启继续录制，“取消”就停止录制，并提示用户注意保存外置SD卡视频
        while (SDCardHelper.getWaiZhiSDCardAvailableSize(waizhiPath)<59586){
            Log.i(TAG,"删除TFCard目录下得文件");
            SDCardHelper.sortFilesByLastModified(this.getApplicationContext(),waizhiPath,2);
//            new AlertDialog.Builder(this).setMessage("可用空间不足，是否执行循环录制？").setNegativeButton("取消",
//                    new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                            new AlertDialog.Builder(MainActivity.this).setMessage("请前往存放视频目录，手动删除不需要的视频，为下一次录制做准备").setNegativeButton("去设置"
//                                    , new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//
////获取父目录
//                                            File parentFlie = new File(pathS);
//                                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                                            intent.setDataAndType(Uri.fromFile(parentFlie), "*/*");
//                                            intent.addCategory(Intent.CATEGORY_OPENABLE);
//                                            startActivity(intent);
//                                        }
//                                    }).create().show();
//                        }
//                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
//                    File file = new File(waizhiPath);
//                    File[] files = file.listFiles();
//                    for (File file1:files){
//                        Log.i(TAG,file1.getName());
//                        file1.delete();
//                    }
//                }
//            }).create().show();
        }








    }
    String pathS;
    public  void startFloatingService(View view){

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (!Settings.canDrawOverlays(this)){
                Toast.makeText(this, "当前无权限请授权!", Toast.LENGTH_SHORT).show();
                startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName())),0);
            }
        } else{

//            Log.i(TAG, "startFloatingService: isRecord="+VideoRecorder.getInstance().isRecord());

            Log.i(TAG, "init: sdcard="+ SDCardHelper.isSDCardMounted());
            Log.i(TAG, "init: path:"+SDCardHelper.getExtSDCardPathList());
            List<String> paths = SDCardHelper.getExtSDCardPathList();
            pathS= Environment.getExternalStorageDirectory().getAbsolutePath();
            for (String path:
                    paths) {
                if (path.contains("sdcard1")){
                    Log.i(TAG, "init: sdcard1="+path);
                    FileUtil.createFile(path+"/DCIM","2.txt");
                    waizhiPath = path;
                    pathS = path+"/DCIM/";
                }
            }
            Log.i(TAG, "init: 全路径="+pathS+System.currentTimeMillis()+".mp4");

            //判断剩余可用空间 如果<20MB,

            Log.i(TAG, "starter: waizhipath="+waizhiPath);
            Log.i(TAG, "starter: available space="+       SDCardHelper.getWaiZhiSDCardAvailableSize(waizhiPath));

            //提示用户可用空间不足，是否开启循环录制，开启继续录制，“取消”就停止录制，并提示用户注意保存外置SD卡视频
            if (SDCardHelper.getWaiZhiSDCardAvailableSize(waizhiPath)<20){
                new AlertDialog.Builder(this).setMessage("可用空间不足，是否执行循环录制？").setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                new AlertDialog.Builder(MainActivity.this).setMessage("请前往存放视频目录，手动删除不需要的视频，为下一次录制做准备").setNegativeButton("去设置"
                                        , new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

//获取父目录
                                                File parentFlie = new File(pathS);
                                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                                intent.setDataAndType(Uri.fromFile(parentFlie), "*/*");
                                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                                startActivity(intent);
                                            }
                                        }).create().show();
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        File file = new File(pathS);
                        File[] files = file.listFiles();
                        for (File file1:files){

                        }
                    }
                }).create().show();
            }else{
                Log.i(TAG, "startFloatingService: start");
                VideoRecorder.getInstance().startRecordVideo(getApplicationContext(),pathS);
            }

//            Log.i(TAG, "startFloatingService: isRecord="+VideoRecorder.getInstance().isRecord());
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0){
            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
                if (!Settings.canDrawOverlays(this)){
                    Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
                    startService(new Intent(this,FloatingService.class));
                }
            }

        }
    }

    public void addUserDb(){
        Context appContext = getApplicationContext();

    }
}
